// pages/list/list_detail/list_detail.js
const app = getApp();
const get = require('../../../utils/common.js')
var WxParse = require('../../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 100,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 800,
    goods_img: [],
    buynum: 1,
    sale_price: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('appidappid',this.data.appid)
    let that = this
    let id = options.id
    let sid = options.sid
    let upopenid = options.upopenid
    that.setData({ upopenid: upopenid })
    console.log(id, sid)
    let openid = wx.getStorageSync('openid')
    var shareopenid = wx.getStorageSync('shareopenid')
    that.setData({ shareopenid })
    var telNum = wx.getStorageSync('telNum')
    if (options.telNum && options.telNum !== 'undefined') {
      telNum = options.telNum
    }
    that.setData({
      openid: openid,
      id: options.id,
      telNum: telNum,
      sid: options.sid // sid为分享过来
    })
    console.log(that.data.telNum)
    let urlId = wx.getStorageSync('urlId')
    let urlOpenid = wx.getStorageSync('urlOpenid')
    if (urlId) { that.setData({ urlId: urlId, sid: urlId }) }//更新sid 为url链接过来
    if (urlOpenid) { that.setData({ urlOpenid: urlOpenid }) }
    wx.getStorage({
      key: 'session_key',
      success(res) {
        console.log("sessin", res.data)
        let session_key = res.data
        that.setData({ session_key: session_key })
        console.log(that.data.session_key, that.data.openid)
      },
      fail(res) {
        console.log(res)
        that.getUserSessionKey()
      }
    })
    console.log(that.data.telNum, that.data.session_key, that.data.openid)

    get.getData('/goods/goodsdetail', { id: sid || id || urlId }).then(res => { //此处sid可能分享过来 可能是 url链接过来
      console.log(res)
      console.log(res.data.data)
      that.setData({
        goodsdetail: res.data.data,
        goods_img: res.data.data.goods_img,
        title_img: res.data.data.title_img,
        goods_name: res.data.data.goods_name,
        goods_desc: res.data.data.goods_desc,
        price: res.data.data.price,
        sale_price: res.data.data.sale_price,
        stock: res.data.data.stock,
        id: res.data.data.id
      })
      console.log(that.data.id)
      var article = res.data.data.detail
      WxParse.wxParse('article', 'html', article, that, 5)
    }).catch(err => {

    })

  },
  // 加入购物车弹窗
  setModalStatus: function (e) {
    // var urlSid=wx.getStorageSync('urlSid') 
    // this.setData({urlSid:urlSid})
    console.log(e)
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatus: true,
        isScroll: false,
      });
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)
  },
  // 加减
  changeNum: function (e) {
    var that = this;
    console.log(e)
    if (e.currentTarget.dataset.alphaBeta == 0) {
      if (this.data.buynum <= 1) {
        buynum: 1
      } else {
        this.setData({
          buynum: that.data.buynum - 1
        })
        console.log(that.data.buynum)
      };
    } else {
      this.setData({
        buynum: that.data.buynum + 1
      })
      console.log(that.data.buynum)
    };
  },
  //进入收藏列表
  shouCang(res) {
    console.log(res)
    wx.redirectTo({
      url: '/pages/list/list',
    })
  },
  //获取session_key和openid
  getUserSessionKey() {
    console.log('必然触发')
    let that = this;
    wx.login({
      success(res) {
        console.log("wx.login", res);
        var code = res.code;
        get.getData('/useractiveprofession/getuserinfo', { code: code }).then(res => {
          console.log(res)
          var session_key = res.data.data.session_key
          var openid = res.data.data.openid
          console.log(session_key, openid)
          that.setData({
            session_key: session_key,
            openid: openid
          })
          console.log(that.data.session_key, that.data.openid)
        }).catch((e) => {
          console.log(e, 'catch')
        })
      }
    })

  },

  //获取手机号码
  getPhoneNumber(e) {
    console.log(e)
    let that = this
    let session_key = that.data.session_key
    let openid = that.data.openid
    let encryptedData = e.detail.encryptedData
    let iv = e.detail.iv
    console.log("openid:", openid)
    console.log("encryptedData:", encryptedData)
    console.log("session_key:", session_key)

    get.getData('/useractiveprofession/gettelnumber', { session_key: session_key, openid: openid, encryptedData: encryptedData, iv: iv }).then(res => {
      console.log(res)
      console.log(res.data.data)
      if (res.data.code == 10008) {
        let telJson = res.data.data
        telJson = JSON.parse(res.data.data)
        let tel = telJson.phoneNumber
        console.log(tel)
        that.onLoginUser(tel)
        wx.setStorage({
          key: 'telNum',
          data: tel
        });
        that.setData({
          telNum: tel
        })
        console.log(555)
      } else {
        console.log(res.data.code)
        wx.showToast({
          title: '请先授权',
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      }
    }).catch(err => {

    })
  },
  //onLoginUser
  onLoginUser(telNum) {
    var that = this
    var openid = that.data.openid
    var urlOpenid = that.data.urlOpenid
    var upopenid = that.data.upopenid || urlOpenid || ''
    var session_key = that.data.session_key
    console.log(openid, session_key, telNum)
    get.getData('/useractiveprofession/userinfo', { openid, session_key, upopenid, tel: telNum }).then(res => {
      console.log("onLoginUser", res)
      that.toPay(telNum)
    }).catch(err => {
      wx.showToast({
        title: '网络异常！err:authlogin',
        duration: 2000
      })
    })


  },
  //确定
  queDing(e) {
    let that = this
    let telNum = that.data.telNum
    if (telNum) {
      that.toPay(telNum)
    }
  },
  //下單 
  toPay(tel) {
    console.log(tel)
    let that = this
    let user_id = that.data.openid
    let goods_id = that.data.id
    let num = that.data.buynum
    // let appid= app.d.appid
    let upopenid = that.data.upopenid || that.data.shareopenid || that.data.urlOpenid || ''
    let params = { user_id: user_id, goods_id: goods_id, num: num, tel: tel}
    // 有时候upopenid会为undefined,所以前面加个判断
    if (upopenid && upopenid !== 'undefined') {
      params.upopenid = upopenid
    }
    console.log('params', params)
    get.getData('/order/order', params).then(res => {
      console.log(res)
      console.log(res.data)
      if (res.data.code == 200) {
        var tip = res.data.msg
        wx.showToast({
          title: tip,
          image: '/pages/images/success.png',
          cancelColor: '#f00',
          mask: false,
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      } else if (res.data.code == 204) {
        var tip = res.data.msg
        wx.showToast({
          title: tip,
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          mask: false,
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      } else {
        var tip = res.data.msg
        wx.showToast({
          title: tip,
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          mask: false,
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      }
    }).catch(err => {
      wx.showToast({
        title: '购买失败',
        image: '/pages/images/fail.png',
        cancelColor: '#f00',
        confirmColor: '#0DD164',
      });
    })


  },
  //隱藏彈窗
  hideModel() {
    let that = this
    console.log(9898)
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: "linear",
      delay: 0
    })
    that.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(that), 200)

  },
  //分享至好友
  onShareAppMessage(options) {
    console.log(options)
    let that = this
    var id = that.data.id
    var openid = that.data.openid
    var title_img = that.data.title_img
    var goods_name = that.data.goods_name
    console.log(id, openid, title_img)
    var shareObj = {
      title: goods_name,
      path: "/pages/login/login?sid=" + id + "&openid=" + openid + "&shareopenid=" + that.data.shareopenid,
      imageUrl: title_img,
    }
    return shareObj
  },

  //回到顶部
  toTop: function (e) {
    console.log(e) // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //回到收藏
  toShoucang(e) {
    console.log(e) // 
    wx.redirectTo({
      url: '/pages/list/list',
    })
  }

})